<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>通义千问 API</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .container {
            max-width: 800px;
            margin-top: 30px;
        }
        .image-result {
            max-width: 100%;
            margin-top: 20px;
        }
        .loading {
            display: none;
        }
        .result-section {
            display: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <h2 class="mb-4">通义千问 API</h2>
        
        <!-- API 配置卡片 -->
        <div class="card mb-4">
            <div class="card-header">
                API 配置
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label for="apiKey" class="form-label">API Key</label>
                    <input type="password" class="form-control" id="apiKey" placeholder="输入��的通义千问 API Key">
                </div>
                <div class="mb-3">
                    <label for="baseUrl" class="form-label">Base URL</label>
                    <input type="text" class="form-control" id="baseUrl" value="https://dashscope.aliyuncs.com/api/v1">
                </div>
                <button class="btn btn-primary" onclick="saveSettings()">保存设置</button>
            </div>
        </div>

        <!-- 模型选择卡片 -->
        <div class="card mb-4">
            <div class="card-header">
                模型选择
            </div>
            <div class="card-body">
                <div class="btn-group w-100" role="group">
                    <button type="button" class="btn btn-outline-primary" onclick="switchMode('text2image')">文生图模式</button>
                    <button type="button" class="btn btn-outline-primary" onclick="switchMode('chat')">对话模式</button>
                </div>
            </div>
        </div>

        <!-- 文生图区域 -->
        <div id="text2imageSection" class="result-section">
            <div class="card mb-4">
                <div class="card-header">
                    文生图
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="imageModel" class="form-label">选择模型</label>
                        <select class="form-select" id="imageModel">
                            <option value="flux-schnell">Flux-Schnell (文生图)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="imagePrompt" class="form-label">图像描述</label>
                        <textarea class="form-control" id="imagePrompt" rows="3" placeholder="请输入您想要生成的图像描述"></textarea>
                    </div>
                    <button class="btn btn-primary" onclick="generateImage()">生成图像</button>
                    
                    <div class="loading mt-3">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <span class="ms-2">正在生成图像，请稍候...</span>
                    </div>

                    <div id="imageContainer" class="mt-4">
                        <img id="imageResult" class="image-result" style="display: none;">
                    </div>
                </div>
            </div>
        </div>

        <!-- 对话区域 -->
        <div id="chatSection" class="result-section">
            <div class="card mb-4">
                <div class="card-header">
                    对话模式
                </div>
                <div class="card-body">
                    <div class="mb-3">
                        <label for="chatModel" class="form-label">选择模型</label>
                        <select class="form-select" id="chatModel">
                            <option value="qwen-turbo">通义千问 Turbo (最快)</option>
                            <option value="qwq-32b-preview">通义千问 QWQ-32B(免费)</option>
                            <option value="qwen-plus">通义千问 Plus (通用)</option>
                            <option value="qwen-max">通义千问 Max (高性能)</option>
                            <option value="qwen-max-1201">通义千问 Max 1201</option>
                            <option value="qwen-max-longcontext">通义千问 Max Long Context</option>
                            <option value="qwen-vl-plus">通义千问 VL Plus (多模态)</option>
                            <option value="qwen-vl-max">通义千问 VL Max (多模态增强)</option>
                            <option value="qwen-7b-chat">通义千问 7B Chat</option>
                            <option value="qwen-14b-chat">通义千问 14B Chat</option>
                            <option value="qwen-72b-chat">通义千问 72B Chat</option>
                            <option value="qwen-1.8b-chat">通义千问 1.8B Chat (轻量)</option>
                            <option value="qwen-audio-chat">通义千问 Audio Chat (语音)</option>
                            <option value="qwen-vl-chat">通义千问 VL Chat (视觉)</option>
                        </select>
                    </div>
                    <div class="mb-3">
                        <label for="chatPrompt" class="form-label">对话内容</label>
                        <textarea class="form-control" id="chatPrompt" rows="3" placeholder="请输入您的问题"></textarea>
                    </div>
                    <button class="btn btn-primary" onclick="sendMessage()">发送消息</button>
                    
                    <div class="loading mt-3">
                        <div class="spinner-border text-primary" role="status">
                            <span class="visually-hidden">加载中...</span>
                        </div>
                        <span class="ms-2">正在处理，请稍候...</span>
                    </div>

                    <div id="chatContainer" class="mt-4">
                        <div id="chatHistory" class="border rounded p-3" style="max-height: 400px; overflow-y: auto;">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 页面加载时加载保存的设置
        document.addEventListener('DOMContentLoaded', function() {
            loadSettings();
            switchMode('text2image'); // 默认显示文生图模式
        });

        // 切换模式
        function switchMode(mode) {
            document.getElementById('text2imageSection').style.display = mode === 'text2image' ? 'block' : 'none';
            document.getElementById('chatSection').style.display = mode === 'chat' ? 'block' : 'none';
            
            // 更新按钮状态
            const buttons = document.querySelectorAll('.btn-group .btn');
            buttons.forEach(button => {
                button.classList.remove('active');
                if ((mode === 'text2image' && button.textContent.includes('文生图')) ||
                    (mode === 'chat' && button.textContent.includes('对话'))) {
                    button.classList.add('active');
                }
            });
        }

        // 保存设置
        function saveSettings() {
            const settings = {
                apiKey: document.getElementById('apiKey').value,
                baseUrl: document.getElementById('baseUrl').value
            };
            localStorage.setItem('aliApiSettings', JSON.stringify(settings));
            alert('设置已保存！');
        }

        // 加载设置
        function loadSettings() {
            const savedSettings = localStorage.getItem('aliApiSettings');
            if (savedSettings) {
                const settings = JSON.parse(savedSettings);
                document.getElementById('apiKey').value = settings.apiKey || '';
                document.getElementById('baseUrl').value = settings.baseUrl || 'https://dashscope.aliyuncs.com/api/v1';
            }
        }

        // 生成图像
        async function generateImage() {
            const settings = JSON.parse(localStorage.getItem('aliApiSettings')) || {};
            const apiKey = document.getElementById('apiKey').value || settings.apiKey;
            const baseUrl = document.getElementById('baseUrl').value || settings.baseUrl;
            const model = document.getElementById('imageModel').value;
            const prompt = document.getElementById('imagePrompt').value;
            const loading = document.querySelector('#text2imageSection .loading');
            const imageResult = document.getElementById('imageResult');

            if (!apiKey || !prompt) {
                alert('请填写 API Key 和图像描述');
                return;
            }

            loading.style.display = 'block';
            imageResult.style.display = 'none';

            try {
                const response = await fetch('/generate_ali_image', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        prompt: prompt,
                        model: model,
                        api_key: apiKey,
                        base_url: baseUrl
                    })
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.detail || '请求失败');
                }

                const data = await response.json();
                console.log('API Response:', data);

                if (data.output && data.output.results && data.output.results.length > 0) {
                    const imageUrl = data.output.results[0].url;
                    if (imageUrl) {
                        imageResult.src = imageUrl;
                        imageResult.style.display = 'block';
                    } else {
                        throw new Error('生成图像失败：未找到图片URL');
                    }
                } else {
                    throw new Error('生成图像失败：响应格式不正确');
                }

            } catch (error) {
                alert('生成图像时出错: ' + error.message);
                console.error('Error details:', error);
            } finally {
                loading.style.display = 'none';
            }
        }

        // 发送消息
        async function sendMessage() {
            const settings = JSON.parse(localStorage.getItem('aliApiSettings')) || {};
            const apiKey = document.getElementById('apiKey').value || settings.apiKey;
            const baseUrl = document.getElementById('baseUrl').value || settings.baseUrl;
            const model = document.getElementById('chatModel').value;
            const prompt = document.getElementById('chatPrompt').value;
            const loading = document.querySelector('#chatSection .loading');
            const chatHistory = document.getElementById('chatHistory');

            if (!apiKey || !prompt) {
                alert('请填写 API Key 和对话内容');
                return;
            }

            loading.style.display = 'block';

            try {
                const response = await fetch('/generate_ali_chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({
                        prompt: prompt,
                        model: model,
                        api_key: apiKey,
                        base_url: baseUrl
                    })
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.detail || '请求失败');
                }

                const data = await response.json();
                console.log('API Response:', data);

                // 添加用户消息
                const userDiv = document.createElement('div');
                userDiv.className = 'mb-3';
                userDiv.innerHTML = `<strong>用户:</strong> ${prompt}`;
                chatHistory.appendChild(userDiv);

                // 添加助手回复
                const assistantDiv = document.createElement('div');
                assistantDiv.className = 'mb-3';
                if (data.choices && data.choices[0] && data.choices[0].message) {
                    const content = data.choices[0].message.content;
                    assistantDiv.innerHTML = `<strong>助手:</strong> ${content}`;
                } else {
                    assistantDiv.innerHTML = '<strong>助手:</strong> 抱歉，我没有得到有效的回复。';
                }
                chatHistory.appendChild(assistantDiv);
                chatHistory.scrollTop = chatHistory.scrollHeight;

            } catch (error) {
                alert('发送消息时出错: ' + error.message);
                console.error('Error details:', error);
            } finally {
                loading.style.display = 'none';
                document.getElementById('chatPrompt').value = ''; // 清空输入框
            }
        }
    </script>
</body>
</html> 